package com.xunwulian.cmpp.client.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.xunwulian.api.iface.AppAPI;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.dubbo.iface.CmppCmebAPI;
import com.xunwulian.dubbo.iface.CmppSmsAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ServiceProvider {

    private static final Logger logger = LoggerFactory.getLogger(ServiceProvider.class);

    @Reference
    private AppAPI appAPI;

    @Autowired
    private CmppSmsAPI cmppSmsAPI;

    @Autowired
    private CmppCmebAPI cmppCmebAPI;

    public AppEntity getApp() {

        // 获取环境变量，平台ID
        String appId = System.getenv("appId");
        if (appId == null || "".equals(appId)) {
            appId = "mock";
        }
        logger.info("appId:" + appId);

        // zk地址
        String registryAddress = System.getenv("registry");
        if (registryAddress == null || "".equals(registryAddress)) {
            registryAddress = "zookeeper://127.0.0.1:2181";
        }
        logger.info("registryAddress:" + registryAddress);

        AppEntity appEntity;
        if ("mock".equals(appId)) {
            appEntity = new AppEntity();
            appEntity.setAppId("mockAppId");
            appEntity.setRegistryAddress("zookeeper://127.0.0.1:2181");
            appEntity.setServerClientId("mockClientId");
            appEntity.setClientSecret("mockClientSecret");
            appEntity.setServerIp("127.0.0.1");
            appEntity.setServerPort("7890");
            appEntity.setDubboPort("20880");
        } else {
            appEntity = (AppEntity) appAPI.getApp(appId).getData();
            logger.info(new Gson().toJson(appEntity));
        }

        return appEntity;
    }

    public void runServer() {
        AppEntity app = getApp();
        // 提供的Cmeb服务
        new Provider<>(cmppCmebAPI, CmppCmebAPI.class, app.getAppId(), app.getAppId(), app.getRegistryAddress(),
                Integer.valueOf(app.getDubboPort()));
        // 提供的Sms服务
        new Provider<>(cmppSmsAPI, CmppSmsAPI.class, app.getAppId(), app.getAppId(), app.getRegistryAddress(),
                Integer.valueOf(app.getDubboPort()));
    }
}
